# import ssl

import flask
from flask_cas import CAS

try:
    from flask import _app_ctx_stack as stack
except ImportError:
    from flask import _request_ctx_stack as stack
from flask import jsonify
from werkzeug.exceptions import HTTPException
from functools import wraps

# ssl._create_default_https_context = ssl._create_unverified_context


class MyCas(CAS):
    @staticmethod
    def login():
        return flask.redirect(flask.url_for('cas.login', _external=True))

    @staticmethod
    def logout():
        return flask.redirect(flask.url_for('cas.logout', _external=True))

    @staticmethod
    def login_required(function):
        @wraps(function)
        def wrap(*args, **kwargs):

            if 'CAS_USERNAME' not in flask.session:
                flask.session['CAS_AFTER_LOGIN_SESSION_URL'] = (
                        flask.request.script_root +
                        flask.request.full_path
                )
                return flask.redirect(flask.url_for('cas.login', _external=True))
            else:
                return function(*args, **kwargs)
                # # 权限校验
                # if permission_check(flask.session['CAS_USERNAME'], flask.request.endpoint):
                #     return function(*args, **kwargs)
                # else:
                #     raise AuthException

        return wrap


def permission_check(username, require_path):
    # 这里修改成你自己的账号和访问权限
    if username == 'suchenhui':
        permission = 'admin'
    else:
        permission = "user"
    if require_path == permission:
        return True
    else:
        return False


class AuthException(HTTPException):
    code = 403
    msg = 'Forbidden To Access This Page!'
    error_code = 1001

    def get_body(self, environ=None, scope=None):
        body = dict(
            msg=self.msg,
            error_code=self.error_code
        )
        return jsonify(body)

    def get_headers(self, environ=None, scope=None):
        """Get a list of headers."""
        return [('Content-Type', 'application/json')]
